<template>
  <div class="z-chart" :style="{ height: height, width: width }"></div>
</template>

<script>
  import resize from './resize';

  export default {
    name: 'z-chart', // 通用的echart组件
    mixins: [resize],
    props: {
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '100%'
      },
      chartOption: {
        type: Object,
        default () {
          return {
            title: {
              text: "世界人口总量",
              left: "center"
            },
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "shadow"
              }
            },
            xAxis: {
              type: "value",
              boundaryGap: [0, 0.01]
            },
            yAxis: {
              type: "category",
              data: ["巴西", "印尼", "美国", "印度", "中国", "世界人口(万)"]
            },
            series: [
              {
                name: "2011年",
                type: "bar",
                data: [18203, 23489, 29034, 104970, 131744, 630230]
              },
              {
                name: "2012年",
                type: "bar",
                data: [19325, 23438, 31000, 121594, 134141, 681807]
              }
            ]
          };
        }
      },
      chartRoot: Object,
    },
    watch: {
      chartOption: {
        deep: true,
        handler (val) {
          if (this.chart) {
            this.setOption(val);
          } else {
            this.initChart();
          }
        }
      }
    },
    data () {
      return {
        chart: null
      };
    },
    methods: {
      /**
       * 初始化图表实例
       */
      initChart () {
        this.chart = this.$echarts.init(this.$el, "custom");
        if (typeof this.chartRoot === 'object') this.chartRoot['chartEle'] = this.chart;
        this.chart.on('datazoom', item => {
          this.$emit('datazoom', item)
        })
        this.setOption(this.chartOption || {});
        this.chart.on("click", param => {
          this.$emit("click", param);
        });
      },

      /**
       * 设置图标的option
       * @param {Object} option
       */
      setOption (option = this.chartOption) {
        this.chart.setOption(option, true);
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.initChart();
      });
    },
    beforeDestroy () {
      if (!this.chart) return;
      this.chart.dispose();
      this.chart = null;
    }
  };
</script>

<style scoped>

</style>
